import MessageBubble from './MessageBubble.js';

class ChatArea {
  constructor(onSendMessage) {
    this.messagesContainer = document.createElement('div');
    this.inputContainer = document.createElement('div');
    this.input = document.createElement('input');
    this.sendButton = document.createElement('button');
    this.onSendMessage = onSendMessage;
    this.userSettings = null;
    this.debateState = {
      status: 'idle', // idle | ready | in_progress | paused | ended
      currentSpeaker: null, // user | character1 | character2
      round: 0,
      topic: null
    };
    this.nextRoundTimer = null;
    this.messageHistory = []; // 用于存储消息历史
    this.setupEventListeners();
  }

  clearNextRoundTimer() {
    if (this.nextRoundTimer) {
      clearTimeout(this.nextRoundTimer);
      this.nextRoundTimer = null;
    }
  }

  async init() {
    const apiService = (await import('../../utils/api.js')).default;
    this.userSettings = await apiService.getUserSettings();
  }

  setupEventListeners() {
    this.sendButton.addEventListener('click', () => {
      const message = this.input.value.trim();
      if (message) {
        const messageData = {
          content: message,
          sender: 'user', // 用户发送的消息始终标记为'user'
          timestamp: Date.now()
        };
        this.onSendMessage(messageData);
        this.input.value = '';

        // 如果是用户发起话题，开始辩论
        if (this.debateState.status === 'ready' && messageData.sender === 'user') {
          this.startDebate(messageData.content);
        }
      }
    });

    this.input.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        this.sendButton.click();
      }
    });
  }

  async startDebate(topic) {
    this.debateState = {
      status: 'in_progress',
      currentSpeaker: 'character1',
      round: 1,
      topic: topic
    };

    // 首先发送用户消息
    const userMessage = {
      content: `本次辩论的话题是：${topic}`,
      sender: 'user',
      timestamp: Date.now()
    };
    this.onSendMessage(userMessage);

    // 获取character1的响应，将用户消息作为上下文
    const apiService = (await import('../../utils/api.js')).default;
    const prompt = `用户设置了辩论话题："${topic}"。请作为正方发表你的观点。并引导反方开始辩论。`;
    const character1Response = await apiService.getChatResponse(prompt, 'character1');

    // 发送character1的响应
    const character1Message = {
      content: character1Response,
      sender: 'character1',
      timestamp: Date.now()
    };
    this.onSendMessage(character1Message);
  }

  async nextRound() {
    console.log('执行下一轮，当前状态:', this.debateState.status);
    // 检查辩论状态
    if (this.debateState.status !== 'in_progress' &&
      this.debateState.status !== 'paused') {
      this.clearNextRoundTimer();
      return;
    }

    this.debateState.round++;
    // 切换发言角色
    this.debateState.currentSpeaker =
      this.debateState.currentSpeaker === 'character1'
        ? 'character2'
        : 'character1';

    console.log('当前发言角色:', this.debateState.currentSpeaker);

    // 获取当前角色的响应，将上一条消息作为上下文
    const apiService = (await import('../../utils/api.js')).default;
    const lastMessage = this.messageHistory[this.messageHistory.length - 1];
    var role = this.debateState.currentSpeaker === 'character1' ? '正方' : '反方';
    const prompt = lastMessage
      ? `上一条消息内容："${lastMessage.content}"。请作为${role}继续辩论。`
      : `请作为${role}就话题"${this.debateState.topic}"发表你的观点`;
    
    const response = await apiService.getChatResponse(
      prompt,
      this.debateState.currentSpeaker
    );

    // 发送当前角色的响应
    const messageData = {
      content: response,
      sender: this.debateState.currentSpeaker,
      timestamp: Date.now()
    };
    this.onSendMessage(messageData);

    // 仅在自动模式下设置定时器
    if (this.debateState.status === 'in_progress') {
      this.clearNextRoundTimer();
      this.nextRoundTimer = setTimeout(() => {
        if (this.debateState.status === 'in_progress') {
          this.nextRound();
        }
      }, 5000);
    }
  }

  async addMessage(messageData) {
    try {
      // 获取发送者头像
      const apiService = (await import('../../utils/api.js')).default;
      const avatar = await apiService.getAvatarForSender(messageData.sender);
      
      // 根据发送者类型获取用户名
      let username;
      if (messageData.sender === 'user') {
        username = this.userSettings?.name || '用户';
      } else {
        const characterSettings = await apiService.getCharacterSettings(messageData.sender);
        username = characterSettings?.name || messageData.sender;
      }
      
      // 确保包含用户信息
      const messageWithUserInfo = {
        ...messageData,
        avatar: avatar,
        username: username
      };
      
      // 将消息存入历史
      this.messageHistory.push(messageWithUserInfo);
      
      const messageBubble = new MessageBubble(messageWithUserInfo);
      this.messagesContainer.appendChild(messageBubble.render());
      this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
    } catch (error) {
      console.error('添加消息失败:', error);
    }
  }

  updateUserSettings(settings) {
    const avatar = this.container.querySelector('.message-avatar');
    if (avatar) {
      avatar.src = settings.avatar || 'assets/images/default-avatar.png';
    }
  }

  render() {
    this.container = document.createElement('div');
    this.container.classList.add('chat-area-container');

    // 消息显示区域
    this.messagesContainer.classList.add('messages-container');
    this.container.appendChild(this.messagesContainer);

    // 输入区域
    this.inputContainer.classList.add('input-container');
    
    this.input.type = 'text';
    this.input.placeholder = '输入消息...';
    this.input.classList.add('message-input');
    this.inputContainer.appendChild(this.input);

    this.sendButton.textContent = '发送';
    this.sendButton.classList.add('send-button');
    this.inputContainer.appendChild(this.sendButton);

    this.container.appendChild(this.inputContainer);

    return this.container;
  }
}

export default ChatArea;
